import { create } from 'zustand';
import { VidUser_ } from '../api/models/VidUser_';
import { refreshUserInfo as refreshUserInfoUtil } from '../utils/auth';

interface UserState {
  userInfo: VidUser_ | null;
  isLoggedIn: boolean;
  isLoading: boolean;
  error: string | null;
}

interface UserActions {
  setUserInfo: (user: VidUser_ | null) => void;
  refreshUserInfo: () => Promise<VidUser_ | null>;
  logout: () => void;
  initializeUser: () => void;
  setLoading: (loading: boolean) => void;
  setError: (error: string | null) => void;
}

type UserStore = UserState & UserActions;

export const useUserStore = create<UserStore>((set, get) => ({
  // 状态
  userInfo: null,
  isLoggedIn: false,
  isLoading: false,
  error: null,

  // 操作
  setUserInfo: (user: VidUser_ | null) => {
    set({ userInfo: user, isLoggedIn: !!user, error: null });
    
    // 同步到localStorage
    if (user) {
      localStorage.setItem('userInfo', JSON.stringify(user));
      localStorage.setItem('isLoggedIn', 'true');
    } else {
      localStorage.removeItem('userInfo');
      localStorage.removeItem('isLoggedIn');
    }
  },

  refreshUserInfo: async (): Promise<VidUser_ | null> => {
    const { setLoading, setError, setUserInfo } = get();
    
    try {
      setLoading(true);
      setError(null);
      
      const refreshedUser = await refreshUserInfoUtil();
      setUserInfo(refreshedUser);
      
      return refreshedUser;
    } catch (error) {
      const errorMessage = error instanceof Error ? error.message : '刷新用户信息失败';
      console.error('刷新用户信息失败:', error);
      setError(errorMessage);
      return null;
    } finally {
      setLoading(false);
    }
  },

  logout: () => {
    set({ 
      userInfo: null, 
      isLoggedIn: false, 
      error: null,
      isLoading: false 
    });
    
    // 清空localStorage
    localStorage.removeItem('userInfo');
    localStorage.removeItem('isLoggedIn');
  },

  initializeUser: () => {
    try {
      const savedUserInfo = localStorage.getItem('userInfo');
      const isLoggedIn = localStorage.getItem('isLoggedIn');

      if (savedUserInfo && isLoggedIn === 'true') {
        const parsedUserInfo = JSON.parse(savedUserInfo);
        set({ 
          userInfo: parsedUserInfo, 
          isLoggedIn: true,
          error: null 
        });
        
        // 页面刷新时获取最新用户信息
        if (parsedUserInfo?.id) {
          get().refreshUserInfo();
        }
      }
    } catch (error) {
      console.error('初始化用户信息失败:', error);
      set({ 
        userInfo: null, 
        isLoggedIn: false, 
        error: '初始化用户信息失败' 
      });
      
      // 清理损坏的数据
      localStorage.removeItem('userInfo');
      localStorage.removeItem('isLoggedIn');
    }
  },

  setLoading: (loading: boolean) => {
    set({ isLoading: loading });
  },

  setError: (error: string | null) => {
    set({ error });
  },
}));

// 导出便捷的hook
export const useUser = () => {
  const store = useUserStore();
  return {
    userInfo: store.userInfo,
    isLoggedIn: store.isLoggedIn,
    isLoading: store.isLoading,
    error: store.error,
    setUserInfo: store.setUserInfo,
    refreshUserInfo: store.refreshUserInfo,
    logout: store.logout,
  };
};

// 初始化用户状态的hook
export const useInitializeUser = () => {
  return useUserStore(state => state.initializeUser);
};